package com.qf.controller;

import com.qf.constant.Constant;
import com.qf.converter.MyDateConverter;
import com.qf.pojo.PageBean;
import com.qf.pojo.User;
import com.qf.responsedata.ResponseResult;
import com.qf.service.AdminService;
import com.qf.service.UserService;
import com.qf.service.impl.AdminServiceImpl;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.JsonUtils;
import com.qf.utils.MD5Utils;
import com.qf.utils.UUIDUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/**
 * 前台用户模块
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {
    //定义子类的方法:add
    /*public void add(HttpServletRequest request,HttpServletResponse response){
        System.out.println("add方法进来了....");
    }*/

    /**
     * 异步校验前台用户名是否可用的功能
     * @param request 请求对象
     * @param response 响应对象
     */
    public void checkUser(HttpServletRequest request,HttpServletResponse response) throws IOException {

        //1)接收参数
        String username = request.getParameter("username");
        //System.out.println(username) ;
        //2)调用用户的业务接口
        UserService userService = new UserServiceImpl() ;
        ResponseResult responseResult = userService.getUser(username);

        //3)将responseResult转换成json
        String jsonStr = JsonUtils.object2json(responseResult) ;
        // System.out.println(jsonStr);
        //4)将jsonStr字符串响应给前端
        response.getWriter().write(jsonStr) ; //{"key":"value"}
    }

    /**
     * 前台用户注册功能
     * @param request  请求对象
     * @param response 响应对象
     */
    public void registerUser(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //1)校验注册的验证码
        //获取前台输入的用户的验证码的内容 name="code"
        String code = request.getParameter("code") ;
        // 从request请求对象获取HttpSession,获取服务器端存储的验证码
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        //一次性验证
        session.removeAttribute("CHECKCODE_SERVER");
        if(code == null || !checkcode_server.equalsIgnoreCase(code)){

            //响应一个json数据到前端
           /* ResponseResult rr = new ResponseResult() ;
            rr.setMsg("验证码错误") ;
            rr.setData(null) ;
            rr.setCode(0) ;
            //解决响应乱码
            response.setContentType("text/html;charset=utf-8");
            //解析json数据
            String s = JsonUtils.object2json(rr);
            System.out.println(s) ;
            response.getWriter().write(s) ;*/
            request.setAttribute("msg","验证码错误") ;
            //请求转发到注册页面上
            request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
            return;
        }


        /*
        一个一个接, 封装User对象,将每一个参数赋值进去
       String username = request.getParameter("username");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        System.out.println(username+"---"+password+"---"+name);*/

        //接收用户其他 ,将用户的数据存储在Map中
        Map<String, String[]> parameterMap = request.getParameterMap(); //参数名称=参数值...
        // System.out.println(parameterMap);
        //commons-beanUtils.jar包 针对实体类进行封装---BeanUtils---populate(Object bean,Map<String,String[]>)
        //创建User对象
        User user = new User() ;
        //System.out.println(user);

        //必须针对birthday这个参数处理----String类型的    ---java.util，Date
        //使用ConvertUtils---->转换器工具----日期转换
        // public static void register(Converter converter, Class<?> clazz)
        // 注册指定的转换: 参数1：转换器接口参数2：最终类型格式
        ConvertUtils.register( new MyDateConverter(), Date.class);
        try {
            BeanUtils.populate(user,parameterMap); // 将自己每一个参数都封装到user对象中
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //System.out.println(user);

        //封装用户的uid---UUID生成的
        user.setUid(UUIDUtils.getId());
        //密码需要处理:加密
        String password = user.getPassword();
        password = MD5Utils.md5(password);
        user.setPassword(password) ;

        //用户的code随机码
        user.setCode(UUIDUtils.getCode());


        //调用UserService
        UserService userService = new UserServiceImpl() ;
        userService.addUser(user) ;

        //请求转发
        request.setAttribute("msg","注册成功,请在注册邮箱进行激活!");
        request.getRequestDispatcher("/message.jsp").forward(request,response);


    }

    /**
     * 前台用户激活功能
     * @param request 请求对象
     * @param response 响应对象
     */
    public void activeUser(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //http://localhost:8080/Maven_2302_war_exploded/user?methodName=activeUser&code=477D3B9AFEA4474B8B044E7DDBAD199D
        //接收参数
        String code = request.getParameter("code");
        //调用UserService
        UserService userService = new UserServiceImpl() ;
        User user = userService.getUserByCode(code);
        System.out.println(user);
        if(user!=null){
            request.setAttribute("msg","用户激活成功,请<a href='"+request.getContextPath()+"/jsp/login.jsp'>登录</a>");

            request.getRequestDispatcher("/message.jsp").forward(request,response);
        }
    }

    /**
     * 前台用户登录功能
     * @param request 请求对象
     * @param response 响应对象
     */
    public void userLogin(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        //1)校验验证码 ,因为验证码存储在服务器端的
        HttpSession session = request.getSession();
        //接收name="code"这个验证码数据
        String code = request.getParameter("code");
        //获取服务器端的存储验证码
        String  checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        //一次性验证
        session.removeAttribute("CHECKCODE_SERVER");
        if("".equals(code) || !checkcode_server.equalsIgnoreCase(code)){
            request.setAttribute("msg","验证码错误!");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
            return;
        }


        //接收用户名和密码
        String username = request.getParameter("username") ;
        String password = request.getParameter("password") ;
        //将密码加密
        password  = MD5Utils.md5(password);

        System.out.println(username+"---"+password);
        //调用UserService
        UserService userService = new UserServiceImpl() ;
        User user = userService.getUseByUserNameAndPwd(username,password) ;
        System.out.println(user);
        if(user == null){
            //提示错误信息
            request.setAttribute("msg","用户名或者密码输入错误!") ;
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
            return;
        }

        //用户不为null
        //判断用户激活状态不是1
        if(user.getState() != Constant.USER_ACTIVE) {
            request.setAttribute("msg","用户状态未激活,请到邮箱先激活") ;
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response) ;
            return;
        }


        //判断用户是否勾选了自动登录
        //获取name="atuoUser"参数
        String autoUser = request.getParameter("autoUser");
        //复选框的默认值auto_user和autoUser进行比较
        if(!"auto_user".equals(autoUser)){
            //没有勾选
            //创建Cookie
            Cookie cookie = new Cookie("autouser","") ;
            //设置最大存活时间 0 ---自动删除cookie
            cookie.setMaxAge(0) ;
            //响应给浏览器
            response.addCookie(cookie) ;
        }else{
            //勾选了
            //存储Cookie
            //定义一个cookie的内容-就是"用户名=密码",
            String content = user.getUsername() +"="+user.getPassword() ;
            //使用jdk工具: 编码器- URLEncoder--->public static String encode(String s, String enc
            //参数1:字符串内容
            //参数2:字符集
            content = URLEncoder.encode(content, "utf-8");
            Cookie cookie = new Cookie("autouser",content) ;

            //设置最大存活时间
            cookie.setMaxAge(60*60*24*30) ;
            //响应给浏览器
            response.addCookie(cookie) ;
        }


        //将用户实体存储在HttpSession中
        session.setAttribute("user",user) ;
        //重定向到/jsp/index.jsp,前台主页
        response.sendRedirect(request.getContextPath()+"/jsp/index.jsp") ;
    }

    /**
     * 前台用户退出功能
     * @param request 请求对象
     * @param response 响应对象
     */
    public void logOut(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //获取HttpSession
        HttpSession session = request.getSession() ;
        //if(session.getAttribute("user")!=null), 加入一个判断,如果session中有"user"信息,销毁
        //将session销毁
        session.invalidate();
        //重定向到/jsp/index.jsp
        response.sendRedirect(request.getContextPath()+"/jsp/index.jsp");
    }

    /**
     * 管理员查询--->分页查询所有用户
     * @param request 请求对象
     * @param response 响应对象
     */
    public void getAllUser(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        //${pageContext.request.contextPath}/user?methodName=getAllUser&curPage=1&pSize=4"
        //1)获取curPage/psize:String类型
        String curPage = request.getParameter("curPage");
        String pSize = request.getParameter("pSize");
        //2)将curPage/pSize--->int
        int currentPage = Integer.parseInt(curPage) ; //当前页码
        int pageSize = Integer.parseInt(pSize) ; //每页显示的条数

        //3)调用AdminService
        AdminService adminService = new AdminServiceImpl() ;
        PageBean<User> pb = adminService.getUserByPage(currentPage, pageSize);
        System.out.println(pb);
        //4)将pb对象存储在request域对象中
        request.setAttribute("pb",pb) ;

        //5)请求转发到 admin/user/user_list.jsp
        request.getRequestDispatcher("/admin/user/user_list.jsp").forward(request,response);
    }


    /**
     * 通过用户uid获取用户
     * @param request  请求对象
     * @param response 响应对象
     */
    public void findUser(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //${pageContext.request.contextPath}/user?methodName=findUser&uid="+uid
        String uid = request.getParameter("uid");
        System.out.println(uid);

        //调用管理员的业务接口
        AdminService adminService = new AdminServiceImpl() ;
        User user = adminService.getUser(uid) ;

        //将user对象存在request域中
        request.setAttribute("user",user) ;
        //请求转发到admin/user/update_user.jsp
        request.getRequestDispatcher("/admin/user/update_user.jsp").forward(request,response);
    }

    /**
     * 更新用户
     * @param request 请求对象
     * @param response 响应对象
     */
    public void updateUser(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        //获取修改的参数
        String uid = request.getParameter("uid");
        String username = request.getParameter("username");
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String sex = request.getParameter("sex");

        //System.out.println(uid+"---"+username+"---"+name+"---"+email+"----"+sex);
        //封装User对象
        User user = new User() ;
        user.setUid(uid) ;
        user.setUsername(username) ;
        user.setName(name) ;
        user.setEmail(email) ;
        user.setSex(sex); ;
        //调用管理员的业务接口
        AdminService adminService = new AdminServiceImpl() ;

        adminService.updateUser(user) ;

        //请求转发到查询所有的服务端地址
        request.getRequestDispatcher("/user?methodName=getAllUser&curPage=1&pSize=4").forward(request,response);
    }

    /**
     * 删除用户
     * @param request 请求对象
     * @param response 响应对象
     */
    public void delUser(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        //${pageContext.request.contextPath}/user?methodName=delUser&uid="+uid
        //接收参数
        String uid = request.getParameter("uid");
        System.out.println(uid);
        //调用业务接口
        AdminService adminService = new AdminServiceImpl() ;
        adminService.deleteUser(uid) ;

        //请求撞到查询后端地址上
        request.getRequestDispatcher("/user?methodName=getAllUser&curPage=1&pSize=4").forward(request,response);
    }
}
